package com.gmail.rborovyk.brightness_widget;

import java.util.ArrayList;

import android.app.Activity;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.RemoteViews;
import android.widget.AdapterView.AdapterContextMenuInfo;

public class ConfigureActivity extends Activity {
	private int mAppWidgetId;
	private Presets mPrefs;
	private ArrayAdapter<Presets.Preset> mAdapter;
	private ArrayList<Presets.Preset> mPresets = new ArrayList<Presets.Preset>();
	private int mSelectedPreset = -1;
	private CheckBox mRiseBrightness;

	private static class NonConfigState {
		Presets Prefs;
		ArrayList<Presets.Preset> Presets;
		
		NonConfigState(Presets prefs, ArrayList<Presets.Preset> presets) {
			Prefs = prefs; Presets = presets;
		}
	}
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setResult(RESULT_CANCELED);
        
        NonConfigState state= (NonConfigState) getLastNonConfigurationInstance();
        if(null != state) {
        	mPrefs = state.Prefs;
        	mPresets = state.Presets;
        }else{
        	mPrefs = new Presets(getApplicationContext());
        	mPresets.addAll(mPrefs.getAllPresets());
        }
        
        if(null != savedInstanceState) {
        	mSelectedPreset = savedInstanceState.getInt("mSelectedPreset");
		}
        
        setContentView(R.layout.configure);
        
        findViewById(R.id.config_add_button).setOnClickListener(mAddListener);
        findViewById(R.id.config_done_button).setOnClickListener(mDoneListener);
        
        ListView lv = (ListView)findViewById(R.id.config_presets_list);
        mAdapter = new ArrayAdapter<Presets.Preset>(
        		this, R.layout.configure_item, 
        		R.id.configure_item_text, mPresets);
        lv.setAdapter(mAdapter);
        registerForContextMenu(lv);
        
        mRiseBrightness = (CheckBox) findViewById(R.id.config_rise_brightness_check);
        mRiseBrightness.setChecked(mPrefs.getRiseBrightness());
        
        Intent intent = getIntent();
        Bundle extras = intent.getExtras();
        if (extras != null) {
            mAppWidgetId = extras.getInt(
                    AppWidgetManager.EXTRA_APPWIDGET_ID, 
                    AppWidgetManager.INVALID_APPWIDGET_ID);
        }
    }
    
    @Override
	public Object onRetainNonConfigurationInstance() {
        return new NonConfigState(mPrefs, mPresets);
    }
    
    @Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putLong("mSelectedPreset", mSelectedPreset);
	}
    
    private View.OnClickListener mAddListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			mSelectedPreset = -1;
			Intent editValue = new Intent(ConfigureActivity.this, BrightnessSetupActivity.class);
			startActivityForResult(editValue, 0);
		}
	};
    
    private View.OnClickListener mDoneListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			if(mRiseBrightness.isChecked() != mPrefs.getRiseBrightness())
				mPrefs.setRiseBrightness(mRiseBrightness.isChecked());
			mPrefs.writePresets();
			
			AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(ConfigureActivity.this);
			RemoteViews views = new RemoteViews(ConfigureActivity.this.getPackageName(), R.layout.widget_initial_layout);
			Intent intent = new Intent(ConfigureActivity.this, BrightnessActivity.class);
			PendingIntent pendingIntent = PendingIntent.getActivity(ConfigureActivity.this, 0, intent, 0);
			views.setOnClickPendingIntent(R.id.widget_button, pendingIntent);
			appWidgetManager.updateAppWidget(mAppWidgetId, views);
			
			Intent resultValue = new Intent();
			resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
			setResult(RESULT_OK, resultValue);
			finish();
		}
	};

	public void onCreateContextMenu (ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.config_context_menu, menu);
		menu.setHeaderTitle(R.string.config_context_title);
		mSelectedPreset = ((AdapterContextMenuInfo) menuInfo).position;
	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		if(-1 == mSelectedPreset)
			return true;
		
		switch (item.getItemId()) {
		case R.id.config_context_edit: {
			Presets.Preset p = mPresets.get(mSelectedPreset);
			Intent editValue = new Intent(this, BrightnessSetupActivity.class);
			editValue.putExtra(BrightnessSetupActivity.PRESET_NAME, p.name);
			editValue.putExtra(BrightnessSetupActivity.PRESET_VALUE, p.value);
			startActivityForResult(editValue, 0);
			return true;
		}
		case R.id.config_context_delete: {
			mPrefs.removePreset(mSelectedPreset);
			updateData();
			return true;
		}
		}
		return super.onContextItemSelected(item);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(RESULT_OK != resultCode)
			return;
		
		String name = data.getStringExtra(BrightnessSetupActivity.PRESET_NAME);
		int value = data.getIntExtra(BrightnessSetupActivity.PRESET_VALUE, 0);
		if(mSelectedPreset >=0) {
			mPrefs.updatePreset(mSelectedPreset, name, value);
		}else{
			mPrefs.addPreset(name, value);
		}
		
		updateData();
	}

	private void updateData() {
		mPresets.clear();
		mPresets.addAll(mPrefs.getAllPresets());
		mAdapter.notifyDataSetChanged();
	}
}